<script setup>
import { ref } from 'vue';
import { sendMessageAsync } from '@/api/user'
const props = defineProps({
  type: {
    type: Number,
    default: 1
  }
})
const emit = defineEmits(['update:modelValue'])

const timer = ref({
  id: '',
  flag: false,
  time: 59
})
const updateValue = (val) => {
  emit('update:modelValue', val)
}
const sendMessage = async () => {
  try {
    if (!phone.value) return ElMessage.error('请先输入可获取短信的手机号码！')
    const reg = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/
    if (!reg.test(phone.value)) return ElMessage.error('请输入正确的手机号码！')

    const params = {
      phone: phone.value,
      type: props.type
    }
    const res = await sendMessageAsync(params)

    if (res && res.code + '' === '200') {
      ElMessage.success('已发送验证码，请注意查收！')
      timer.value.flag = true
      timer.value.id = setInterval(() => {
        if (timer.value.flag) {
          if (timer.value.time === 0) {
            clearInterval(timer.value.id)
            timer.value.flag = false
            timer.value.time = 59
          } else {
            timer.value.time--
          }
        }
      }, 1000)

    } else if (res && res.code + '' !== '200') {
      ElMessage.error(res.msg)
    }

  } catch (error) {
    console.log('%c [ error ]-23', 'font-size:13px; background:pink; color:#bf2c9f;', error)

  }
}

const phone = ref('')
</script>

<template>
  <div class="code-container">
    <el-input v-bind="$attrs" v-model="phone" @change="updateValue" />
    <el-button type="primary" :class="{ getCode: timer.flag }" class="btn-red" @click="sendMessage"
      :disabled="timer.flag">
      {{ timer.flag ? `${timer.time}秒后重新获取验证码` : '获取验证码' }}
    </el-button>
  </div>
</template>

<style lang="scss" scoped>
.code-container {
  display: flex;

  .getCode {
    // height: 50px;
    white-space: pre-wrap;
    width: 100px !important;

  }
}

:deep(.el-input) {
  width: 150px !important;
}

:deep(.el-button) {
  margin-left: 10px;
  font-size: 12px !important;
  font-weight: 400 !important;
  width: 70px !important;

}
</style>